package org.canaan.http.urlpair.core;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;

/**
 * @author Canaan
 * @date 2017/6/29 0029
 */
 public final class Utils {

    /**
     * 是否为基础常量
     *
     * @param o
     * @return
     */
    public static boolean isBaseType(Object o) {
        if (BigInteger.class.isInstance(o)) {
            return  true;
        }else if (Integer.class.isInstance(o)) {
            return true;
        } else if (String.class.isInstance(o)) {
            return true;
        } else if (Float.class.isInstance(o)) {
            return true;
        } else if (Double.class.isInstance(o)) {
            return true;
        } else if (Short.class.isInstance(o)) {
            return true;
        } else if (Long.class.isInstance(o)) {
            return true;
        } else if (Character.class.isInstance(o)) {
            return true;
        } else if (Boolean.class.isInstance(o)) {
            return true;
        } else if (Byte.class.isInstance(o)) {
            return true;
        } else if(BigDecimal.class.isInstance(o)){
            return true;
        } else if (null == o) {
            return true;
        }
        return false;
    }




    public static Object urlEncoder(Object object){
        if(object==null){return  "";}
        if (String.class.isInstance(object)) {
            try {
                return URLEncoder.encode(object.toString(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
        return object;
    }

    /**
     * 把中文转成Unicode码
     *
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            if (chr1 >= 128 && chr1 <= 171941) {//汉字范围 \u4e00-\u9fa5 (中文)
                String unicode = String.valueOf(Integer.toHexString(chr1));
                result.append("\\u").append(formatUnicode(unicode));
            } else {
                result.append(str.charAt(i));
            }
        }
        return result.toString();
    }

    /**
     * 格式化成unicode的格式
     *
     * @param unicode
     * @return
     */
    public static String formatUnicode(String unicode) {
        int length = 4 - unicode.length();
        for (int i = 0; i < length; i++) {
            unicode = "0" + unicode;
        }
        return unicode;
    }

}
